package server;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Map;

/**
 * @author songyi
 * @date 2020/6/28 0028 17:50
 * @description 请求处理类
 */
public class RequestProcessor extends Thread {

    private Socket socket;
    // private Map<String, HttpServlet> servletMap;
    private Mapper mapper;

    /*public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap) {
        this.socket = socket;
        this.servletMap = servletMap;
    }*/

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            // 封装request和response对象
            Request request = new Request(inputStream);
            Response response = new Response(outputStream);
            String host = request.getHost();
            String url = request.getUrl();
            String[] split = url.split("/");
            //项目名为context
            String context = split[1];
            String servletName = url.substring(context.length() + 1);
            MappedHost mappedHost = mapper.getHostMap().get(host);
            MappedContext mappedContext = mappedHost.getContextMap().get(context);
            HttpServlet httpServlet = mappedContext.getServletMap().get(servletName);
            // 静态资源处理
            if (httpServlet == null) {
                response.outputHtml(request, mapper);
            } else {
                // 动态资源servlet处理
                httpServlet.service(request, response);
            }
            inputStream.close();
            outputStream.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
